<?php
/**
 * 订单接口
 * @author maniac
 */
namespace app\api\controller\v1;

use app\facade\Orders AS OrdersFacade;
use think\Db;
use think\Exception;
use think\facade\Env;
use app\common\model\OrderGoods;
use app\common\model\Orders as OrdersModel;
class Orders extends Base
{


    /**
     * 确认订单
     */
    public function confirmOrder(){
        $post = input('post.');
        $goods =input('goods','');//商品
//        $goods =[[ "goods_id" => 48, "goods_nums" => 10, "goods_sku_id" =>"7:27;8:30", "goods_sku_name" =>"儿童票;10月12号" ]  ];
        $buy_id =input('buy_id','');//购物车
        $post['userid'] = $this->checkUserToken();

        if (empty($goods)) {
            return j(1, '请选择要购买的商品');
        }
        try {
            $data = OrdersFacade::confirmOrder($post);
            return j(0, '获取成功', $data);
        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }
    }

	/**
	 * 邮费
	 */
	public function confirmPostage(){
//		$post['userid'] = $this->checkUserToken();
		$post['goods'] =input('goods','');//商品
		$post['store_id'] = input('store_id','');//商户
		$post['address'] = input('address',0);//地址ID
		if (empty($post['goods'])) {
			return j(1, '请选择要购买的商品');
		}
		try {
			$data = OrdersFacade::confirmPostage($post);
			return j(0, '获取成功', $data);
		} catch (\Exception $e) {
			return j(1, $e->getMessage());
		}
	}

    public function ceshi(){
        $post['userid'] = rand(10,25);
        $post['goods'][0] = array(
            "goods_id"=>1,
            "goods_sku_id"=>40,
            "goods_nums"=>1);
        $post['buyType'] = 1;
        $post['coupon_id'] = 0;
        $post['user_address_id'] = 26;
        $post['store_id'] = 0;
        $post['order_type'] = 1;
        try {
//            dump($post);die;
            $data = OrdersFacade::add($post);
            return j(0, '添加订单成功', $data);
        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }

    }


    /**
     * 添加订单
     */
    public function add()
    {
        $post = input('post.');
        $post['userid'] = $this->checkUserToken();
        $post['buyType'] = input('buyType',1);//订单类型
        $post['coupon_id'] = 0;//优惠券ID
        $post['order_type'] = input('order_type',1);//订单类型
        $post['store_id'] = 0;//门店id;
        if (!(int)$post['user_address_id']) {
            return j(1, '请选择收货地址');
        }
        if (empty($post['goods'])) {
            return j(1, '请选择要购买的商品');
        }
        Db::startTrans();
        try {
            $data = OrdersFacade::add($post);
            Db::commit();
            return j(0, '兑换成功', $data);
        } catch (\Exception $e) {
            Db::rollback();
            return j(1, $e->getMessage());
        }
    }
    
    /**
     * 获取订单列表
     */
    public function orderList()
    {

        $userId     = $this->checkUserToken();
        $isShipping = input('post.is_shipping/d', 0);
        $tabIndex   = input('post.tabIndex/d', 0);
        $page       = input('post.page/d', 1);
        $limit      = input('post.limit/d', 10);
        $order_type = input('order_type',0);
        // 分页偏移量
        $offset     = ($page - 1) * $limit;
        $limit      = $offset.','.$limit;

        try {
            $data = OrdersFacade::orderList($userId, $limit, $tabIndex, $isShipping,$order_type);
            return j(0, '获取订单信息成功', $data);
        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }
    }
    
    /**
     * 获取未支付订单
     */
    public function payOrder()
    {
        $userId = $this->checkUserToken();

        $id     = input('post.id/d', 1);

        try {
            $data = OrdersFacade::payOrder($userId, $id);
            return j(0, '获取订单信息成功', $data);
        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }
    }
    /*
     * 订单详情
     * @author 董伟
     * */
    public function order_detail(){

        $userId = $this->checkUserToken();
//        $userId = input('user_id');
        $id     = input('post.id/d', 1);
        try {
            $data = OrdersFacade::orderInfo($id,$userId);
            return j(0, '获取订单信息成功', $data);
        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }
    }
//删除订单
    public function orderDelete(){
        $user_id = $this->checkUserToken();
        $order_id = input('order_id');
        Db::startTrans();
        try {
            $order = OrdersModel::where("userid",$user_id)->where("id",$order_id)->field('id,is_user_delete,order_status')->find();
            if (empty($order)){
                \exception("订单不存在");
            }
            if ($order['is_user_delete']){
                \exception("订单已被删除");
            }
            $order->is_user_delete = 1;

            $order->save();
            Db::commit();
            return j(0,"删除成功");
        } catch (Exception $exception) {
            Db::rollback();
            return j(1,$exception->getMessage());
        }
    }

    
    /**
     * 确认收货
     */
    public function confirmGoods()
    {
        $userId = $this->checkUserToken();
        $id     = input('post.id/d', 1);
        try {
            $result = OrdersFacade::confirmGoods($userId, $id);
            if ($result) {
                return j(0, '确认收货成功');
            }
            return j(1, '确认收货失败');
        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }
    }

    /**
     * 取消订单
     */
    public function cancelOrder()
    {
        $userId = $this->checkUserToken();
//        $userId     =input('user_id');
        $id     = input('post.id/d', 1);
        try {
            $result = OrdersFacade::cancelOrder($userId, $id);
            if ($result) {
                return j(0, '成功');
            }
            return j(1, '失败');
        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }
    }

    
    public function qrcode()
    {
        $userId = $this->checkUserToken();
        $id     = input('post.id/d', 0);
        $file   = './static/uploads/qrcode/pay_'.$id.'.png';
        if (!file_exists($file)) {
            $rootPath = str_replace('\\', '/', Env::get('root_path'));
            require $rootPath.'extend/phpqrcode/phpqrcode.php';
            $value = 'http://xcx.msblpsd.com/wxpay/'.$id;
    		$errorCorrectionLevel = "L";
    		$matrixPointSize = 10;
    		\QRcode::png($value, $file, $errorCorrectionLevel, $matrixPointSize,2);
        }
        return j(0, '生成二维码成功', config('system.attach_uri_prefix').ltrim($file, './'));
    }

    //退款
    public function refund(){
        $userId = $this->checkUserToken();

        $order_ids = input('order_ids',0);
        $order_id = input('order_id',0);

        $r_type   =input('r_type',1);//1申请退款，2申请退款退货
        $user_message   =input('user_message',"");//申请留言

        $arr=[
            'r_type'=>$r_type,
            'user_message'=>$user_message,
        ];
        try {
            $result = OrdersFacade::refund($userId,$order_id,$order_ids,$arr);//用户ID，订单ID，订单商品ID
            if ($result) {
                return j(0, '成功');
            }
            return j(1, '申请失败');
        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }
    }

    /**
     * 填写物流号
     */
    public function setWNumbers(){
        $userId = $this->checkUserToken();

        $order_id = input('order_id',0);
        $back__num = input('back_num','');//物流单号
        $back_company = input('back_company','');//物流公司

        $arr=[
            'userid'=>$userId,
            'order_id'=>$order_id,
            'back_num'=>$back__num,
            'back_company'=>$back_company
        ];
        try {
            $result = OrdersFacade::setWNumbers($arr);//用户ID，订单ID，订单商品ID
            if ($result) {
                return j(0, '成功');
            }
            return j(1, '申请失败');
        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }
    }


    /**
     * 核销码
     */
    public function order_code(){
        $userId = $this->checkUserToken();
        $id = input('id',0);

        try {
            $result = OrdersFacade::order_code($id);//用订单ID
            if ($result) {
                return j(0, '成功');
            }
            return j(1, '申请失败');
        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }
    }


    /**
     * 核销订单
     */
    public function is_verification(){
        $userId = $this->checkUserToken();
        $id = input('id',0);
        try {
            $result = OrdersFacade::is_verification($userId,$id);//用订单ID
            if ($result) {
                return j(0, '成功');
            }
            return j(1, '核销失败');
        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }
    }


    /**
     * 核销列表
     */
    public function order_verification(){
        $userId = $this->checkUserToken();
        $type = input('type',0);//状态 0未核销1已核销
        try {
            $result = OrdersFacade::order_verification($userId,$type);//用户ID，状态

            return j(0, '成功',$result);

        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }
    }




}
